Skip to main content

nodejs 使用 SSL

使用生成证书

$ mkcert -install
Created a new local CA at "/Users/filippo/Library/Application Support/mkcert" 💥
The local CA is now installed in the system trust store! ⚡️
The local CA is now installed in the Firefox trust store (requires browser restart)! 🦊

$ mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1
Using the local CA at "/Users/filippo/Library/Application Support/mkcert"

Created a new certificate valid for the following names 📜
- "example.com"
- "*.example.com"
- "example.test"
- "localhost"
- "127.0.0.1"
- "::1"

The certificate is at "./example.com+5.pem" and the key at "./example.com+5-key.pem"

把证书放入node项目的ssl目录

配置文件

var express = require("express");
var http = require("http");
var https = require("https");
var fs = require("fs");

var app = express();

app.get('/',function(req,res){
res.send('hhhhh');
})

httpsOption = {
key : fs.readFileSync("./ssl/ajtest.dianzu.me+2-key.pem"),
cert: fs.readFileSync("./ssl/ajtest.dianzu.me+2.pem"),
}

http.createServer(app).listen(80);
https.createServer(httpsOption, app).listen(443);

运行 https://127.0.0.1 即可